/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package viewControl;

import entity.Fag;
import entity.Hold;
import entity.Holdfag;
import entity.HoldfagId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import util.GUIUtils;

/**
 *
 * @author Jeppe
 */
public class HoldPanel extends javax.swing.JPanel {

    private Session session;
    private ArrayList fag;
    private ArrayList holdFag;
    private boolean needtoupdate;

    /**
     * Creates new form HoldPanel
     */
    public HoldPanel(Session session) {
        this.session = session;
        needtoupdate = false;
        fag = new ArrayList();
        holdFag = new ArrayList();
        initComponents();
    }

    protected void update() {
        Hold holdIndex = null;
        if (cbHold.getSelectedIndex() > 0) {
            holdIndex = (Hold) cbHold.getSelectedItem();
        }
        cbHold.setSelectedIndex(0);
        holdFag = new ArrayList();
        fag = new ArrayList();
        cbHold.removeAllItems();
        cbHold.addItem("Hold");
        String hql = "from Hold";
        try {
            Query q = session.createQuery(hql);
            List resultList = q.list();
            for (int i = 0; i < resultList.size(); i++) {
                cbHold.addItem((Hold) resultList.get(i));
            }
        } catch (HibernateException he) {
            System.out.println(he.getLocalizedMessage());
        }
        GUIUtils.clearFields(this);
        updateFag(false);
        if (holdIndex != null) {
            cbHold.setSelectedItem(holdIndex);
        } else {
            cbHold.setSelectedIndex(0);
        }

    }

    public void updateFag(boolean medhold) {
        if (!medhold) {
            String hql = "from Fag";
            try {
                fag.clear();
                Query q = session.createQuery(hql);
                Object[] fList = q.list().toArray();
                Arrays.sort(fList);
                fag.addAll(Arrays.asList(fList));
            } catch (HibernateException he) {
                System.out.println(he.getLocalizedMessage());
            }
            listFag.setListData(fag.toArray());
        }
        if (medhold) {
            updateFag(false);
            for (int i = 0; i < holdFag.size(); i++) {
                Fag f1 = (Fag) holdFag.get(i);

                for (int j = 0; j < fag.size(); j++) {
                    Fag f2 = (Fag) fag.get(j);

                    if (f1.getNavn().equals(f2.getNavn())) {

                        fag.remove(f2);
                    }
                }
            }
            listFag.setListData(fag.toArray());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cbHold = new javax.swing.JComboBox();
        btnOpretHold = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        listHoldFag = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        btnTilfojFag = new javax.swing.JButton();
        btnFjernFag = new javax.swing.JButton();
        txtNytFagNavn = new javax.swing.JTextField();
        btnOpretFag = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        listFag = new javax.swing.JList();
        btnSletFag = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        btnSletHold = new javax.swing.JButton();
        btnGemHold = new javax.swing.JButton();

        setLayout(null);

        cbHold.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Hold" }));
        cbHold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbHoldActionPerformed(evt);
            }
        });
        add(cbHold);
        cbHold.setBounds(10, 11, 150, 20);

        btnOpretHold.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnOpretHold.setText("Opret nyt hold");
        btnOpretHold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpretHoldActionPerformed(evt);
            }
        });
        add(btnOpretHold);
        btnOpretHold.setBounds(170, 10, 120, 23);

        jScrollPane1.setViewportView(listHoldFag);

        add(jScrollPane1);
        jScrollPane1.setBounds(10, 100, 150, 230);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Fag på hold:");
        add(jLabel1);
        jLabel1.setBounds(10, 80, 80, 14);

        btnTilfojFag.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnTilfojFag.setText("<<Tilføj fag");
        btnTilfojFag.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTilfojFagActionPerformed(evt);
            }
        });
        add(btnTilfojFag);
        btnTilfojFag.setBounds(170, 140, 110, 23);

        btnFjernFag.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnFjernFag.setText("Fjern fag>>");
        btnFjernFag.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFjernFagActionPerformed(evt);
            }
        });
        add(btnFjernFag);
        btnFjernFag.setBounds(170, 260, 110, 23);
        add(txtNytFagNavn);
        txtNytFagNavn.setBounds(460, 100, 210, 20);

        btnOpretFag.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnOpretFag.setText("Opret nyt fag");
        btnOpretFag.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpretFagActionPerformed(evt);
            }
        });
        add(btnOpretFag);
        btnOpretFag.setBounds(460, 130, 110, 23);

        listFag.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Dansk", "Engelsk", "Tysk", "Matematik", "OSV" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(listFag);

        add(jScrollPane2);
        jScrollPane2.setBounds(290, 100, 150, 230);

        btnSletFag.setText("Slet fag");
        btnSletFag.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSletFagActionPerformed(evt);
            }
        });
        add(btnSletFag);
        btnSletFag.setBounds(600, 130, 70, 23);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Eksisterende fag:");
        add(jLabel2);
        jLabel2.setBounds(290, 80, 100, 14);

        jLabel3.setText("Navn på nyt fag:");
        add(jLabel3);
        jLabel3.setBounds(460, 80, 90, 14);
        add(jSeparator1);
        jSeparator1.setBounds(0, 50, 1160, 20);

        btnSletHold.setText("Slet hold");
        btnSletHold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSletHoldActionPerformed(evt);
            }
        });
        add(btnSletHold);
        btnSletHold.setBounds(300, 10, 73, 23);

        btnGemHold.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnGemHold.setText("Gem fag på hold");
        btnGemHold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGemHoldActionPerformed(evt);
            }
        });
        add(btnGemHold);
        btnGemHold.setBounds(10, 350, 150, 30);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSletHoldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSletHoldActionPerformed
        int result = JOptionPane.showConfirmDialog(null, "Er du sikker på du vil slette Hold " + (cbHold.getItemCount() - 1) + "\n(Det vil altid være det hold sidste hold på listen der slettes)", "Advarsel", 2);
        if (result == JOptionPane.OK_OPTION) {
            if (((Hold) cbHold.getItemAt(cbHold.getItemCount() - 1)).getElevs().isEmpty()) {
                session.beginTransaction();
                Hold hold = (Hold) cbHold.getItemAt(cbHold.getItemCount() - 1);
                session.delete(hold);
                session.getTransaction().commit();
                session.flush();
                update();
            } else {
                JOptionPane.showMessageDialog(null, "Kan ikke slette hold da det stadig har elever tilknyttet", "Info", 2);
            }

        }
    }//GEN-LAST:event_btnSletHoldActionPerformed

    private void btnOpretHoldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpretHoldActionPerformed
        session.beginTransaction();
        Hold hold = new Hold(cbHold.getItemCount());
        session.save(hold);
        session.getTransaction().commit();
        session.flush();
        update();
        cbHold.setSelectedIndex(cbHold.getItemCount() - 1);
    }//GEN-LAST:event_btnOpretHoldActionPerformed

    private void btnOpretFagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpretFagActionPerformed
        if (txtNytFagNavn.getText().length() > 0) {
            Fag nytfag = new Fag();
            nytfag.setNavn(txtNytFagNavn.getText());
            session.beginTransaction();
            session.save(nytfag);
            session.getTransaction().commit();
            session.flush();
            update();
        }

    }//GEN-LAST:event_btnOpretFagActionPerformed

    private void btnSletFagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSletFagActionPerformed
        if (listFag.getSelectedIndex() >= 0) {
            int result = JOptionPane.showConfirmDialog(null, "Er du sikker på du vil slette det valgte fag?", "Advarsel", 2);
            if (result == JOptionPane.OK_OPTION) {
                Fag fag = (Fag) listFag.getSelectedValue();
                session.beginTransaction();
                session.refresh(fag);
                session.getTransaction().commit();

                if (fag.getHoldfags().isEmpty()) {
                    if (fag.getTrinoverskrifts().isEmpty()) {
                        session.beginTransaction();
                        session.delete(listFag.getSelectedValue());
                        session.getTransaction().commit();

                        update();
                    } else {
                        JOptionPane.showMessageDialog(null, "Kan ikke slette fag da det har trinmål", "Info", 2);
                    }

                } else {
                    JOptionPane.showMessageDialog(null, "Kan ikke slette fag da det stadig er aktivt på et hold", "Info", 2);
                }

            }
        }
    }//GEN-LAST:event_btnSletFagActionPerformed

    private void btnGemHoldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGemHoldActionPerformed
        needtoupdate = false;
        if (cbHold.getSelectedIndex() > 0) {

            session.beginTransaction();
            Hold hold = (Hold) cbHold.getSelectedItem();
            hold.getHoldfags().removeAll(hold.getHoldfags());
            session.update(hold);
            session.getTransaction().commit();

            session.beginTransaction();
            for (int i = 0; i < holdFag.size(); i++) {
                HoldfagId hfid = new HoldfagId(hold.getId(), ((Fag) holdFag.get(i)).getId());
                Holdfag hf = new Holdfag(hfid, ((Fag) holdFag.get(i)), hold);
                hold.getHoldfags().add(hf);

            }
            session.update(hold);
            session.getTransaction().commit();
            session.flush();
            int index = cbHold.getSelectedIndex();
            update();
            cbHold.setSelectedIndex(index);
            JOptionPane.showMessageDialog(null, "Holdet er gemt.", "Info", 1);
        }
    }//GEN-LAST:event_btnGemHoldActionPerformed

    private void cbHoldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbHoldActionPerformed
        holdFag = new ArrayList();
        listHoldFag.setListData(holdFag.toArray());
        if (cbHold.getSelectedIndex() > 0) {
            Hold hold = (Hold) cbHold.getSelectedItem();
            ArrayList temp = new ArrayList();
            temp.addAll(hold.getHoldfags());
            for (int i = 0; i < temp.size(); i++) {
                Fag f = ((Holdfag) temp.get(i)).getFag();
                holdFag.add(f);

            }
            listHoldFag.setListData(holdFag.toArray());
            needtoupdate = true;
            updateFag(true);
        } else {
            if (needtoupdate) {
                update();
                needtoupdate = false;
            }
        }

    }//GEN-LAST:event_cbHoldActionPerformed

    private void btnTilfojFagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTilfojFagActionPerformed
        if (cbHold.getSelectedIndex() > 0 && listFag.getSelectedValue() != null) {
            Fag f = (Fag) fag.get(listFag.getSelectedIndex());
            holdFag.add(f);
            fag.remove(listFag.getSelectedIndex());
            listHoldFag.setListData(holdFag.toArray());
            listFag.setListData(fag.toArray());
        }
    }//GEN-LAST:event_btnTilfojFagActionPerformed

    private void btnFjernFagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFjernFagActionPerformed
        if (listHoldFag.getSelectedValue() != null) {
            Fag f = (Fag) holdFag.get(listHoldFag.getSelectedIndex());

            fag.add(f);
            holdFag.remove(listHoldFag.getSelectedIndex());
            listFag.setListData(fag.toArray());
            listHoldFag.setListData(holdFag.toArray());
        }
    }//GEN-LAST:event_btnFjernFagActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnFjernFag;
    private javax.swing.JButton btnGemHold;
    private javax.swing.JButton btnOpretFag;
    private javax.swing.JButton btnOpretHold;
    private javax.swing.JButton btnSletFag;
    private javax.swing.JButton btnSletHold;
    private javax.swing.JButton btnTilfojFag;
    private javax.swing.JComboBox cbHold;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JList listFag;
    private javax.swing.JList listHoldFag;
    private javax.swing.JTextField txtNytFagNavn;
    // End of variables declaration//GEN-END:variables
}
